﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Xml;
using System.Net;
using System.IO;
using JiraConnector.executor;


namespace JiraConnector
{
    public class JIRAConnector
    {

        /// <summary>
        /// returns JIRAIssueList for the requested url
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="url"></param>
        /// <returns></returns>
      public static JIRAIssueList getJIRAIssues(String username, String password, String url)
        {
            try
            {
                string svcCredentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(username + ":" + password));

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Headers.Add("Authorization", "Basic " + svcCredentials);
                request.AllowAutoRedirect = true;

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream resStream = response.GetResponseStream();
                StreamReader objSR;
                objSR = new StreamReader(resStream, System.Text.Encoding.GetEncoding("utf-8"));

                //JSON example 
                string json = objSR.ReadLine();

                //var jiraIssues = Newtonsoft.Json.Linq.JObject.Parse(json);

                JIRAIssueList issues = Newtonsoft.Json.JsonConvert.DeserializeObject<JIRAIssueList>(json);
                issues.json = json;
                return issues;
            }
            catch (Exception ex)
            {
                //TODO: log the error
                throw ex; 
                //throw new JiraConnectorException(ex);
            }
        }


    }
}
